<template>
  <div class="circulation">
    <!-- 主容器：使用Grid表格布局 -->
    <div class="circulation-grid">
      <!-- 表头行 -->
      <template v-for="(pillar, colIndex) in pillars" :key="`header-${colIndex}`">
        <div class="grid-header" :style="{ gridColumn: getColumnIndex(colIndex) }">
          {{ pillar.label || `柱${colIndex + 1}` }}
        </div>
        <!-- 水平关系列（在柱子之间） -->
        <template v-if="colIndex < pillars.length - 1">
          <div class="grid-relation-horizontal" :style="{ gridColumn: getColumnIndex(colIndex, true) }"></div>
        </template>
      </template>

      <!-- 天干标签行 -->
      <template v-for="(pillar, colIndex) in pillars" :key="`gan-label-${colIndex}`">
        <div class="grid-gan-label" :style="{ gridColumn: getColumnIndex(colIndex) }">
          {{ pillar.ganLabel || '' }}
        </div>
        <template v-if="colIndex < pillars.length - 1">
          <div class="grid-relation-horizontal" :style="{ gridColumn: getColumnIndex(colIndex, true) }"></div>
        </template>
      </template>

      <!-- 天干字符行 -->
      <template v-for="(pillar, colIndex) in pillars" :key="`gan-${colIndex}`">
        <div class="grid-gan-cell" :style="{ gridColumn: getColumnIndex(colIndex), color: getTianganColor(pillar.gan) }">
          {{ pillar.gan }}
        </div>
        <!-- 天干水平关系 -->
        <template v-if="colIndex < pillars.length - 1">
          <div class="grid-relation-horizontal" :style="{ gridColumn: getColumnIndex(colIndex, true) }">
            <img
              v-if="getHorizontalRelationImage(colIndex, colIndex + 1, 'gan')"
              :src="getHorizontalRelationImage(colIndex, colIndex + 1, 'gan')"
              class="relation-image horizontal"
              :alt="'天干关系'"
            />
          </div>
        </template>
      </template>

      <!-- 垂直关系行 -->
      <template v-for="(pillar, colIndex) in pillars" :key="`vertical-${colIndex}`">
        <div class="grid-relation-vertical" :style="{ gridColumn: getColumnIndex(colIndex) }">
          <img
            v-if="getVerticalRelationType(colIndex)"
            :src="getVerticalRelationImage(colIndex)"
            class="relation-image vertical"
            :alt="getVerticalRelationType(colIndex)?.type || ''"
          />
        </div>
        <template v-if="colIndex < pillars.length - 1">
          <div class="grid-relation-horizontal" :style="{ gridColumn: getColumnIndex(colIndex, true) }"></div>
        </template>
      </template>

      <!-- 地支字符行 -->
      <template v-for="(pillar, colIndex) in pillars" :key="`zhi-${colIndex}`">
        <div class="grid-zhi-cell" :style="{ gridColumn: getColumnIndex(colIndex), color: getDizhiColor(pillar.zhi) }">
          {{ pillar.zhi }}
        </div>
        <!-- 地支水平关系 -->
        <template v-if="colIndex < pillars.length - 1">
          <div class="grid-relation-horizontal" :style="{ gridColumn: getColumnIndex(colIndex, true) }">
            <img
              v-if="getHorizontalRelationImage(colIndex, colIndex + 1, 'zhi')"
              :src="getHorizontalRelationImage(colIndex, colIndex + 1, 'zhi')"
              class="relation-image horizontal"
              :alt="'地支关系'"
            />
          </div>
        </template>
      </template>

      <!-- 地支标签行 -->
      <template v-for="(pillar, colIndex) in pillars" :key="`zhi-label-${colIndex}`">
        <div class="grid-zhi-label" :style="{ gridColumn: getColumnIndex(colIndex) }">
          {{ pillar.zhiLabel || '' }}
        </div>
        <template v-if="colIndex < pillars.length - 1">
          <div class="grid-relation-horizontal" :style="{ gridColumn: getColumnIndex(colIndex, true) }"></div>
        </template>
      </template>
    </div>

    <!-- 图例图片 -->
    <div class="legend-image">
      <img :src="gzrLtTips" alt="图例" class="legend-img" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { 
  isTianganSheng,
  isTianganZhu,
  isTianganKe,
  isTianganHe,
  isTianganChong,
  isDizhiSheng,
  isDizhiZhu,
  isDizhiLiuhe,
  isDizhiChong,
  isDizhiXing,
  isDizhiPo,
  isDizhiHai,
  isPillarSheng,
  isPillarZhu,
  isWuxingSheng,
  isDizhiBanhe,
  isDizhiGonghe,
  isDizhiAnheJu,
  isDizhiAnSanhui
} from '@/utils/ganzhi-relations'
import { getTianganColor, getDizhiColor, GANZHI_WUXING } from '@/utils/wuxing'

// 导入关系图片
import chongHengxiang from '@/assets/circulation/冲-横向.png'
import chongShuzhe from '@/assets/circulation/冲-竖着.png'
import heHengxiang from '@/assets/circulation/合-横向.png'
import keHengxiang from '@/assets/circulation/克-横向.png'
import keShuzhe from '@/assets/circulation/克-竖着.png'
import shengHengxiangXiangyou from '@/assets/circulation/生-横着-向右.png'
import shengHengxiangXiangzuo from '@/assets/circulation/生-横着-向左.png'
import shengShuzheXiangshang from '@/assets/circulation/生-竖着-向上.png'
import shengShuzheXiangxia from '@/assets/circulation/生-竖着-向下 copy.png'
import xingHengxiang from '@/assets/circulation/刑-横向.png'
import xingShuzhe from '@/assets/circulation/刑-竖着.png'
import zhuHengxiang from '@/assets/circulation/助-横向.png'
import zhuShuzhe from '@/assets/circulation/助-竖着.png'
import gzrLtTips from '@/assets/circulation/gzr_lt_tips.png'

interface Pillar {
  gan: string
  zhi: string
  label?: string
  ganLabel?: string
  zhiLabel?: string
}

interface Props {
  pillars: Pillar[]
}

const props = defineProps<Props>()

// 五行相克关系映射
const WUXING_KE: Record<string, string[]> = {
  '木': ['土'],
  '火': ['金'],
  '土': ['水'],
  '金': ['木'],
  '水': ['火']
}

// 关系类型到图片key的映射
const RELATION_TYPE_MAP: Record<string, string> = {
  '三合': '合',
  '五合': '合',
  '六合': '合',
  '相生': '生',
  '相助': '助',
  '相冲': '冲',
  '相刑': '刑',
  '相破': '刑', // 暂时使用相刑的图片
  '相害': '刑', // 暂时使用相刑的图片
  '相克': '克'
}

// 计算Grid列索引
// 柱子列：1, 3, 5, 7 (1-based)
// 关系列：2, 4, 6 (1-based)
const getColumnIndex = (colIndex: number, isRelation: boolean = false): string => {
  if (isRelation) {
    // 关系列：colIndex * 2 + 2
    return `${colIndex * 2 + 2}`
  } else {
    // 柱子列：colIndex * 2 + 1
    return `${colIndex * 2 + 1}`
  }
}

// 获取垂直关系类型（天干到地支之间）
const getVerticalRelationType = (colIndex: number): { type: string; direction?: 'up' | 'down' } | null => {
  const pillar = props.pillars[colIndex]
  if (!pillar) return null
  
  const gan = pillar.gan
  const zhi = pillar.zhi
  const ganWx = GANZHI_WUXING[gan]
  const zhiWx = GANZHI_WUXING[zhi]
  
  if (!ganWx || !zhiWx) return null
  
  // 判断相生方向：gan生zhi为向下，zhi生gan为向上
  if (isWuxingSheng(ganWx, zhiWx)) {
    return { type: '相生', direction: 'down' } // 天干生地支，向下
  } else if (isWuxingSheng(zhiWx, ganWx)) {
    return { type: '相生', direction: 'up' } // 地支生天干，向上
  } else if (isPillarZhu(gan, zhi)) {
    return { type: '相助' }
  } else if (WUXING_KE[ganWx]?.includes(zhiWx) || WUXING_KE[zhiWx]?.includes(ganWx)) {
    return { type: '相克' }
  }
  
  return null
}

// 获取水平关系类型（两个柱子之间）
const getHorizontalRelationType = (
  index1: number, 
  index2: number, 
  type: 'gan' | 'zhi'
): { type: string; direction?: 'left' | 'right' } | null => {
  const pillar1 = props.pillars[index1]
  const pillar2 = props.pillars[index2]
  if (!pillar1 || !pillar2) return null
  
  if (type === 'gan') {
    const gan1 = pillar1.gan
    const gan2 = pillar2.gan
    
    if (isTianganHe(gan1, gan2)) {
      return { type: '五合' }
    } else if (isTianganChong(gan1, gan2)) {
      return { type: '相冲' }
    } else if (isTianganSheng(gan1, gan2)) {
      return { type: '相生', direction: 'right' } // gan1生gan2，向右
    } else if (isTianganSheng(gan2, gan1)) {
      return { type: '相生', direction: 'left' } // gan2生gan1，向左
    } else if (isTianganZhu(gan1, gan2)) {
      return { type: '相助' }
    } else {
      // 使用五行相克关系判断（更可靠）
      const gan1Wx = GANZHI_WUXING[gan1]
      const gan2Wx = GANZHI_WUXING[gan2]
      if (gan1Wx && gan2Wx) {
        if (WUXING_KE[gan1Wx]?.includes(gan2Wx) || WUXING_KE[gan2Wx]?.includes(gan1Wx)) {
          return { type: '相克' }
        }
      }
    }
  } else if (type === 'zhi') {
    const zhi1 = pillar1.zhi
    const zhi2 = pillar2.zhi
    
    // 先检查半合关系（三合局缺少中间地支）
    const banhe = isDizhiBanhe(zhi1, zhi2)
    if (banhe.isBanhe) {
      return { type: '三合' } // 半合也使用三合的图片
    }
    
    // 检查暗合局（暗三合）- 需要天干配合，优先检测
    const ganlist = props.pillars.map(p => p.gan).filter((gan): gan is string => !!gan)
    const anheJu = isDizhiAnheJu(zhi1, zhi2, ganlist)
    if (anheJu.isAnheJu) {
      return { type: '三合' } // 暗合局也使用三合的图片
    }
    
    // 检查暗三会局 - 需要天干配合，优先检测
    const anSanhui = isDizhiAnSanhui(zhi1, zhi2, ganlist)
    if (anSanhui.isAnSanhui) {
      return { type: '三会' } // 暗三会局使用三会的图片
    }
    
    // 检查拱合局（拱三合）- 如果暗合局不满足，才检测拱合
    const gonghe = isDizhiGonghe(zhi1, zhi2)
    if (gonghe.isGonghe) {
      return { type: '三合' } // 拱合也使用三合的图片
    }
    
    if (isDizhiLiuhe(zhi1, zhi2)) {
      return { type: '六合' }
    } else if (isDizhiChong(zhi1, zhi2)) {
      return { type: '相冲' }
    } else if (isDizhiXing(zhi1, zhi2)) {
      return { type: '相刑' }
    } else if (isDizhiPo(zhi1, zhi2)) {
      return { type: '相破' }
    } else if (isDizhiHai(zhi1, zhi2)) {
      return { type: '相害' }
    } else if (isDizhiSheng(zhi1, zhi2)) {
      return { type: '相生', direction: 'right' } // zhi1生zhi2，向右
    } else if (isDizhiSheng(zhi2, zhi1)) {
      return { type: '相生', direction: 'left' } // zhi2生zhi1，向左
    } else if (isDizhiZhu(zhi1, zhi2)) {
      return { type: '相助' }
    } else {
      // 检查相克关系（基于五行）
      const zhi1Wx = GANZHI_WUXING[zhi1]
      const zhi2Wx = GANZHI_WUXING[zhi2]
      if (zhi1Wx && zhi2Wx) {
        if (WUXING_KE[zhi1Wx]?.includes(zhi2Wx) || WUXING_KE[zhi2Wx]?.includes(zhi1Wx)) {
          return { type: '相克' }
        }
      }
    }
  }
  
  return null
}

// 获取水平关系图片（两个柱子之间）
const getHorizontalRelationImage = (
  index1: number, 
  index2: number, 
  type: 'gan' | 'zhi'
): string | undefined => {
  const relation = getHorizontalRelationType(index1, index2, type)
  if (!relation) return undefined
  
  const relationKey = RELATION_TYPE_MAP[relation.type]
  if (!relationKey) return undefined
  
  // 根据关系类型和方向返回对应图片
  if (relationKey === '生') {
    // 根据方向选择向左或向右图片
    if (relation.direction === 'right') {
      return shengHengxiangXiangyou // 向右
    } else if (relation.direction === 'left') {
      return shengHengxiangXiangzuo // 向左
    }
    // 默认向右（从左到右）
    return shengHengxiangXiangyou
  } else if (relationKey === '冲') {
    return chongHengxiang
  } else if (relationKey === '合') {
    return heHengxiang
  } else if (relationKey === '克') {
    return keHengxiang
  } else if (relationKey === '刑') {
    return xingHengxiang
  } else if (relationKey === '助') {
    return zhuHengxiang
  }
  
  return undefined
}

// 获取垂直关系图片（根据方向选择向上或向下）
const getVerticalRelationImage = (colIndex: number): string | undefined => {
  const relation = getVerticalRelationType(colIndex)
  if (!relation) return undefined
  
  const relationKey = RELATION_TYPE_MAP[relation.type]
  if (!relationKey) return undefined
  
  // 根据关系类型和方向返回对应图片
  if (relationKey === '生') {
    // 根据方向选择向上或向下图片
    if (relation.direction === 'up') {
      return shengShuzheXiangshang // 向上
    } else if (relation.direction === 'down') {
      return shengShuzheXiangxia // 向下
    }
    // 默认向下（兼容旧代码）
    return shengShuzheXiangxia
  } else if (relationKey === '助') {
    return zhuShuzhe
  } else if (relationKey === '克') {
    return keShuzhe
  } else if (relationKey === '刑') {
    return xingShuzhe
  } else if (relationKey === '冲') {
    return chongShuzhe
  }
  
  return undefined
}

// 获取关系图片（兼容函数，实际使用 getHorizontalRelationImage 和 getVerticalRelationImage）
const getRelationImage = (
  type: string, 
  position: 'top' | 'bottom' | 'left' | 'right'
): string | undefined => {
  const isVertical = position === 'top' || position === 'bottom'
  const isHorizontal = position === 'left' || position === 'right'
  
  // 获取关系key
  const relationKey = RELATION_TYPE_MAP[type]
  if (!relationKey) return undefined
  
  // 根据方向和关系类型返回对应图片
  if (isVertical) {
    // 竖着方向（上下）- 这个函数现在主要用于兼容，实际垂直关系使用 getVerticalRelationImage
    if (relationKey === '生') return shengShuzheXiangxia // 默认向下
    if (relationKey === '助') return zhuShuzhe
    if (relationKey === '克') return keShuzhe
    if (relationKey === '刑') return xingShuzhe
    if (relationKey === '冲') return chongShuzhe
    return undefined
  } else if (isHorizontal) {
    // 横向方向（左右）- 这个函数现在主要用于兼容，实际水平关系使用 getHorizontalRelationImage
    if (relationKey === '冲') return chongHengxiang
    if (relationKey === '合') return heHengxiang
    if (relationKey === '克') return keHengxiang
    if (relationKey === '生') return shengHengxiangXiangyou // 默认向右
    if (relationKey === '刑') return xingHengxiang
    if (relationKey === '助') return zhuHengxiang
  }
  
  return undefined
}
</script>

<style scoped>
.circulation {
  background: #fff;
  position: relative;
  min-height: 400px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  overflow-x: auto; /* 如果内容超出，允许横向滚动 */
}

/* 主容器：使用Grid表格布局 */
.circulation-grid {
  display: grid;
  grid-template-columns: 1fr minmax(0, 111px) 1fr minmax(0, 111px) 1fr minmax(0, 111px) 1fr; /* 柱子列自适应，关系列可缩小 */
  grid-template-rows: auto auto auto auto auto auto; /* 表头、天干标签、天干字符、垂直关系、地支字符、地支标签 */
  gap: 0;
  width: 100%;
  max-width: 100%;
  padding: 20px 0;
  justify-items: center;
  align-items: center;
  box-sizing: border-box;
}

/* 表头单元格 */
.grid-header {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: 14px;
  padding: 8px 4px;
  min-height: 20px;
  box-sizing: border-box;
  max-width: 100%;
}

/* 天干标签单元格 */
.grid-gan-label {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: 12px;
  padding: 4px;
  min-height: 20px;
}

/* 天干字符单元格 */
.grid-gan-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  font-size: 28px;
  font-weight: 700;
  box-sizing: border-box;
  max-width: 100%;
}

/* 垂直关系单元格 */
.grid-relation-vertical {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: auto;
  min-height: 33px; /* 垂直高度 = 横向高度 */
}

/* 地支字符单元格 */
.grid-zhi-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  font-size: 28px;
  font-weight: 700;
  padding: 10px 0;
  box-sizing: border-box;
  max-width: 100%;
}

/* 地支标签单元格 */
.grid-zhi-label {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: 12px;
  padding: 4px;
  min-height: 20px;
}

/* 水平关系单元格（柱子之间的缝隙） */
.grid-relation-horizontal {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 0;
  max-width: 100%;
  box-sizing: border-box;
  overflow: hidden; /* 防止内容溢出 */
}

/* 关系图片通用样式 */
.relation-image {
  pointer-events: none;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  display: block;
  object-fit: contain;
}

/* 横向图片（左右方向）：111 * 33，自适应容器 */
.relation-image.horizontal {
  width: 100%;
  max-width: 100%;
  height: auto;
  max-height: 33px; /* 最大高度不超过原始尺寸 */
  object-fit: contain;
}

/* 竖着图片（上下方向）：高度与横向图片高度一致 */
.relation-image.vertical {
  width: auto;
  max-width: 23px; /* 保持原始宽度比例 */
  height: auto;
  min-height: 74px; /* 最小高度 */
  max-height: 33px; /* 垂直高度 = 横向高度 */
  object-fit: contain;
}

/* 图例图片 */
.legend-image {
  display: flex;
  width: 100%;
}

.legend-img {
  width: 307px;
  height: 62px;
  display: block;
  margin-left: 10px;
}

</style>
